// pages/profile/edit.js
Page({
    data: {
      loading: false,
      avatarChanged: false,  // 标记头像是否修改
      tempAvatar: null,      // 临时头像文件路径
      formData: {
        avatar: '',         // 最终头像URL
        nickname: '',
        mobile: '',
        email: '',
        gender: 0
      }
    },
  
    onLoad() {
      this.loadUserData()
    },
  
    // 加载初始数据
    async loadUserData() {
      const res = await wx.request({
        url: 'https://api.example.com/user/profile'
      })
      this.setData({
        'formData.avatar': res.data.avatar,
        'formData.nickname': res.data.nickname,
        'formData.mobile': res.data.mobile,
        'formData.email': res.data.email,
        'formData.gender': res.data.gender
      })
    },
  
    // 选择头像
    async chooseAvatar() {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image']
      })
      this.setData({
        tempAvatar: res.tempFiles[0].tempFilePath,
        avatarChanged: true
      })
    },
  
    // 上传头像到服务器
    async uploadAvatar() {
      if (!this.data.avatarChanged) return null
      
      const uploadRes = await wx.uploadFile({
        url: 'https://api.example.com/upload/avatar',
        filePath: this.data.tempAvatar,
        name: 'avatar'
      })
      
      const res = JSON.parse(uploadRes.data)
      if (res.code !== 0) throw new Error('头像上传失败')
      return res.data.url
    },
  
    // 提交表单
    async submitForm(e) {
      this.setData({ loading: true })
      
      try {
        // 1. 上传头像
        const newAvatar = await this.uploadAvatar()
        
        // 2. 准备提交数据
        const submitData = {
          ...e.detail.value,
          avatar: newAvatar || this.data.formData.avatar
        }
  
        // 3. 提交用户信息
        await wx.request({
          url: 'https://api.example.com/user/profile',
          method: 'PUT',
          data: submitData
        })
  
        wx.showToast({ title: '保存成功' })
        setTimeout(() => wx.navigateBack(), 1500)
      } catch (err) {
        wx.showToast({ title: err.message, icon: 'none' })
      } finally {
        this.setData({ loading: false })
      }
    }
  })